<template>
  <div class="app-container">
    <div>
      <el-button type="primary" @click="addList">新增项目 </el-button>
      <el-button type="warning" @click="importFN">批量导入</el-button>
    </div>
    <br />
    <div>
      <el-table
        v-loading="loading"
        :data="list"
        :border="show"
        :row-key="getRowKeys"
        @row-click="clickRowHandle"
        :expand-row-keys="expands"
      >
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column
          label="项目名称"
          prop="name"
          align="center"
          min-width="120"
        />
        <el-table-column
          label="项目类型"
          prop="type"
          align="center"
          min-width="120"
        >
          <template #default="scope">
            <p v-if="scope.row.type == 0">个人</p>
            <p v-if="scope.row.type == 1">团体</p>
            <p v-if="scope.row.type == 2">团队竞技</p>
            <p v-if="scope.row.type == 3">混双</p>
            <p v-if="scope.row.type == 4">混合团体</p>
            <p v-if="scope.row.type == 5">混合个人</p>
            <p v-if="scope.row.type == 6">混合团队竞技</p>
          </template>
        </el-table-column>
        <el-table-column
          label="是否有组别"
          prop="type"
          align="center"
          min-width="120"
        >
          <template #default="scope">
            <div v-if="scope.row?.hasNext == 1">是</div>
            <div v-else>否</div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding"
          width="300"
        >
          <template #default="scope">
            <el-button
              v-if="scope.row.hasNext != 0"
              type="text"
              @click="updateRow(scope.row)"
              >添加组别</el-button
            >
            <el-button type="text" @click="viewRow(scope.row)">编辑</el-button>
            <el-button type="text" @click="delRow(scope.row)">删除</el-button>
            <el-button
              v-if="scope.row.hasNext != 0"
              type="text"
              @click="particulars(scope.row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="initData"
      />
    </div>

    <!-- 添加级别 -->
    <el-dialog
      v-model="showDialog"
      width="30%"
      append-to-body
      center
      draggable
      @close="close"
      v-if="showDialog"
      :title="form.id ? '编辑级别' : '添加级别'"
    >
      <el-form ref="formRef" :model="form" label-width="120px" :rules="rules">
        <el-form-item label="级" prop="name" v-if="form.type == 1">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="组" prop="name" v-else>
          <el-input v-model="form.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="btnOkFN">确 定</el-button>
          <el-button type="warning" @click="close">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showTree"
      width="30%"
      append-to-body
      center
      draggable
      @close="close"
      v-if="showTree"
      title="批量导入"
    >
      <div>
        <el-tree
          :props="props"
          :load="loadNode"
          ref="tree"
          node-key="id"
          lazy
          show-checkbox
          @check-change="treeFn"
        />
        <br />
        <el-row justify="center">
          <el-button type="primary" @click="treeOk">确 定</el-button>
          <el-button type="warning" @click="treeClose">取 消</el-button>
        </el-row>
      </div>
    </el-dialog>

    <!-- 子表 -->
    <el-dialog
      v-model="showDialogOther"
      width="80%"
      append-to-body
      center
      draggable
      @close="closeOther"
      v-if="showDialogOther"
    >
      <div>
        <el-table :data="listGroup" :border="true" stripe>
          <el-table-column label="组名" prop="name" align="center" width="120">
          </el-table-column>
          <el-table-column label="组" align="center" width="210">
            <template #default="props">
              <div v-if="props.row?.hasNext != 0">
                <p v-if="props.row?.levelType == 0">通用组</p>
                <p v-else>男女组</p>
                <p>年龄({{ props.row.birthPeriod }})</p>
              </div>
              <p v-else>年龄({{ props.row.birthPeriod }})</p>
            </template>
          </el-table-column>
          <el-table-column label="级别">
            <template #default="props">
              <div v-if="props.row?.hasNext != 0">
                <div v-if="props.row.maleLevelList">
                  男子组：<el-tag
                    @click="updateClass(item)"
                    @close="handleClose(item)"
                    class="mx-1 tag"
                    closable
                    v-for="item in props.row.maleLevelList"
                    :key="item.id"
                    >{{ item.name }}</el-tag
                  >
                  <el-button
                    v-if="props.row?.hasSon == 0"
                    size="small"
                    type="info"
                    round
                    @click="
                      addGroup(
                        props.row.maleLevelList,
                        props.row.id,
                        props.row.cptId,
                        1
                      )
                    "
                    >+</el-button
                  >
                  <div v-else>
                    级别：<el-tag
                      @click="updateRank(item)"
                      @close="delRank(item)"
                      class="mx-1 tag"
                      closable
                      v-for="item in props?.row?.maleLevelList[0]
                        ?.maleSonLevelList"
                      :key="item.id"
                      >{{ item.name }}</el-tag
                    >
                    <el-button
                      size="small"
                      type="info"
                      round
                      @click="addRank(props.row.maleLevelList)"
                      >+</el-button
                    >
                  </div>
                </div>

                <div v-if="props.row.femaleLevelList">
                  女子组：<el-tag
                    class="mx-1 tag"
                    closable
                    @click="updateClass(item)"
                    @close="handleClose(item)"
                    v-for="item in props.row.femaleLevelList"
                    :key="item.id"
                    >{{ item.name }}</el-tag
                  >
                  <el-button
                    v-if="props.row?.hasSon == 0"
                    size="small"
                    type="info"
                    round
                    @click="
                      addGroup(
                        props.row.femaleLevelList,
                        props.row.id,
                        props.row.cptId,
                        2
                      )
                    "
                    >+</el-button
                  >
                  <div v-else>
                    级别：<el-tag
                      @click="updateRank(item)"
                      @close="delRank(item)"
                      class="mx-1 tag"
                      closable
                      v-for="item in props?.row?.femaleLevelList[0]
                        ?.maleSonLevelList"
                      :key="item.id"
                      >{{ item.name }}</el-tag
                    >
                    <el-button
                      size="small"
                      type="info"
                      round
                      @click="addRank(props.row.femaleLevelList)"
                      >+</el-button
                    >
                  </div>
                </div>
                <div v-else>
                  组别：<el-tag
                    @click="updateClass(item)"
                    @close="handleClose(item)"
                    class="mx-1 tag"
                    closable
                    v-for="item in props.row.commonList"
                    :key="item.id"
                    >{{ item.name }}</el-tag
                  >
                  <el-button
                    v-if="props.row?.hasSon == 0"
                    size="small"
                    type="info"
                    round
                    @click="
                      addGroup(
                        props.row.commonList,
                        props.row.id,
                        props.row.cptId,
                        0
                      )
                    "
                    >+</el-button
                  >
                  <div v-else>
                    级别：<el-tag
                      @click="updateRank(item)"
                      @close="delRank(item)"
                      class="mx-1 tag"
                      closable
                      v-for="item in props?.row?.commonList[0]
                        ?.commonSonLevelList"
                      :key="item.id"
                      >{{ item.name }}</el-tag
                    >
                    <el-button
                      size="small"
                      type="info"
                      round
                      @click="addRank(props.row.commonList)"
                      >+</el-button
                    >
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template #default="props">
              <el-button type="text" @click="updateGroup(props.row)"
                >编辑</el-button
              >
              <el-button type="text" @click="DelClass(props.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { getCurrentInstance } from "vue";
import { reactive } from "@vue/runtime-core";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import {
  getList,
  getGroup,
  addGroupChi,
  imputApi,
  getImportApi,
  delApi,
  delGroupApi,
  UpdateClassApi,
  delClass,
  delCompetitionSonLevel,
  updateSonLevel,
  addSonLevel,
} from "@/api/match/CompetitionProject.js";

const showDialogOther = ref(false);
const route = useRoute();
const router = useRouter();
const id = ref(route.query.id);
const baseProjectId = ref(route.query.baseProjectId);
const signType = ref(route.query.signType);
const { proxy } = getCurrentInstance();
const total = ref(0);
const show = ref(false);
const list = ref([]);
const groutId = ref();
const listGroup = ref([]);
const showDialog = ref(false);
const showTree = ref(false);
const type = ref();
const expands = ref([]);
const props = {
  label: "name",
  isLeaf: "id",
};
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cptId: id.value,
  },
  form: {},
  rules: {
    name: [{ required: true, message: "级别不能为空", trigger: "blur" }],
  },
  treeFrom: {},
});
const { queryParams, form, rules, treeFrom } = toRefs(data);

initData();
// 赛事项目列表
async function initData() {
  let res = await getList(queryParams.value);
  total.value = res.total;
  list.value = res.rows;
}

// 添加组别
function updateRow(row) {
  router.push({
    path: "/match/competitionadd",
    query: {
      cptId: row.cptId,
      indx: 1,
      cptProjectId: row.id,
      signType: row.type,
    },
  });
}

// 新增
function addList() {
  router.push({
    path: "/match/competitionadd",
    query: { cptId: id.value, signType: signType.value },
  });
}

// 刷新
async function refresh() {
  form.value.cptProjectId = groutId.value;
  let res = await getGroup(form.value);
  listGroup.value = res.rows;
  form.value = {};
}

// 新增级别
function addGroup(row, groupId, cptId, levelType) {
  showDialog.value = true;
  form.value.cptGroupId = groupId;
  form.value.cptId = cptId;
  form.value.levelType = levelType;
}
// 新增级下级
function addRank(row) {
  // 添加拆分级别
  console.log(row);
  form.value.type = 1;
  form.value.parentLevelId = row[0].id;
  form.value.name = "";
  showDialog.value = true;
  console.log(form.value);
}

// 子级别删除
function delRank(item) {
  // delCompetitionSonLevel
  proxy.$modal
    .confirm('是否确认删除级别"' + item.name + '"的数据项？')
    .then(async function () {
      form.value.ids = item.id;
      await delCompetitionSonLevel(form.value);
    })
    .then(async () => {
      await refresh();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
  // console.log(item);
}

function close() {
  form.value = {};
  showDialog.value = false;
}

// 确定|新增级别|编辑级别
function btnOkFN() {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (valid) {
      let res = null;
      if (form.value.type) {
        if (form.value.id) {
          // 修改
          res = await updateSonLevel(form.value);
        } else {
          // 添加
          res = await addSonLevel(form.value);
        }
      } else {
        if (form.value.id) {
          // 修改
          res = await UpdateClassApi(form.value);
        } else {
          // 添加
          res = await addGroupChi(form.value);
        }
      }

      if (res.code == 200) {
        proxy.$modal.msgSuccess("操作成功");
        close();
        refresh();
      } else {
        proxy.$modal.msgError("操作失败");
      }
    } else {
      proxy.$modal.msgError("请完善信息");
    }
  });
}

// 批量导入
function importFN() {
  showTree.value = true;
}

// 查看批量导入数据
async function loadNode(node, resolve) {
  let res = "";
  switch (node.level) {
    case 0:
      form.value.id = baseProjectId.value;
      form.value.level = 0;
      form.value.trainId = id;
      res = await getImportApi(form.value);
      if (res.data) {
        let list = res.data;
        return resolve(list);
      } else {
        resolve([]);
      }
      break;
    case 1:
      form.value.id = node.data.id;
      form.value.level = 1;
      form.value.trainId = id;
      res = await getImportApi(form.value);
      if (res.data) {
        let list = res.data;
        return resolve(list);
      } else {
        resolve([]);
      }
      break;
    case 2:
      form.value.id = node.data.id;
      form.value.level = 2;
      form.value.trainId = id;
      res = await getImportApi(form.value);
      if (res.data) {
        let list = res.data;
        _.each(list, (l) => {
          l.parentId = node.data.id;
        });
        return resolve(list);
      } else {
        resolve([]);
      }
      break;
    case 3:
      form.value.id = node.data.id;
      form.value.level = 3;
      form.value.trainId = id;
      res = await getImportApi(form.value);
      if (res.data) {
        let list = res.data;
        return resolve(list);
      } else {
        resolve([]);
      }
      break;
    default:
      resolve([]);
      break;
  }
}

// 批量导入，确定
async function treeOk() {
  let selectedNodes = proxy.$refs["tree"].getCheckedNodes(false, true);
  let arr0 = [];
  let arr1 = [];
  let arr2 = [];
  let arr3 = [];
  selectedNodes.forEach((item) => {
    console.log(item);
    if (item.level == 1) {
      arr1.push(item.id);
    } else if (item.level == 2) {
      arr2.push(item.id);
    } else if (item.level == 3) {
      arr3.push(item.id);
    } else if (item.level == 0) {
      arr0.push(item.id);
    }
  });

  let tree = {};
  tree.node1 = arr1;
  tree.node2 = arr2;
  tree.node3 = arr3;
  treeFrom.value.map = tree;
  treeFrom.value.id = id.value;
  treeFrom.value.cptId = arr0[0];
  let res = await imputApi(treeFrom.value);
  if (res.code === 200) {
    proxy.$modal.msgSuccess("操作成功");
    treeClose();
  } else {
    proxy.$modal.msgError("操作失败");
  }
}

// 取消
function treeClose() {
  showTree.value = false;
  initData();
}

// 赛事项目删除
async function delRow(row) {
  proxy.$modal
    .confirm('是否确认删除组名称为"' + row.name + '"的数据项？')
    .then(async function () {
      form.value.ids = row.id;
      await delApi(form.value);
    })
    .then(async () => {
      await initData();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
}

// 删除级组
async function DelClass(row) {
  proxy.$modal
    .confirm(
      '是否确认删除培训名称为"' +
        (row.levelType == 1 ? "男女组" : "通用组") +
        '"的数据项？'
    )
    .then(async function () {
      form.value.ids = row.id;
      await delGroupApi(form.value);
    })
    .then(async () => {
      await refresh();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
}

// 编辑项目
function viewRow(row) {
  router.push({
    path: "/match/competitionadd",
    query: {
      cptProjectId: row.id,
      cptId: row.cptId,
      signType: signType.value,
    },
  });
}

// 编辑组
function updateGroup(row) {
  router.push({
    path: "/match/competitionadd",
    query: {
      groupId: row.id,
      indx: 1,
      cptProjectId: row.cptProjectId,
      cptId: row.cptId,
      signType: type.value,
    },
  });
}

// 点击组
function updateClass(row) {
  form.value = JSON.parse(JSON.stringify(row));
  form.value.parentLevelId = row.id;
  form.value.type = null;
  showDialog.value = true;
}

// 点击级
function updateRank(row) {
  form.value = JSON.parse(JSON.stringify(row));
  form.value.type = 1;
  console.log(form.value);
  showDialog.value = true;
}

function getRowKeys(row) {
  return row.id;
}

// 展开
async function clickRowHandle(row) {
  if (expands.value.includes(row.id)) {
    expands.value = expands.value.filter((val) => val !== row.id);
  } else {
    expands.value.push(row.id);
    type.value = row.type;
  }
}

// 删除级
async function handleClose(row) {
  proxy.$modal
    .confirm("是否确认删除级别为" + row.name + "的数据项？")
    .then(async function () {
      form.value.ids = row.id;
      await delClass(form.value);
    })
    .then(async () => {
      await refresh();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
}

// 子表
async function particulars(row) {
  showDialogOther.value = true;
  form.value.cptProjectId = row.id;
  groutId.value = row.id;
  let res = await getGroup(form.value);
  listGroup.value = res.rows;
  form.value = {};
}
</script>

<style lang="scss" scoped>
.left {
  margin-right: 30px;
}

.tag {
  margin-right: 10px;
  margin-bottom: 10px;
}
.box {
  padding: 0 50px;
}
</style>
